package com.eh.taxation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eh.taxation.entity.Question;
import com.eh.taxation.entity.Subject;
import com.eh.taxation.mapper.QuestionMapper;
import com.eh.taxation.service.QuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eh.taxation.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 问题 服务实现类
 * </p>
 *
 * @author erhuo
 * @since 2021-01-21
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    @Autowired
    private SubjectService subjectService;

    @Override
    public List<Question> getHotQuestion() {
        QueryWrapper<Question> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("view_count");
        wrapper.last("limit 8");
        List<Question> list = baseMapper.selectList(wrapper);
        return list;
    }

    @Override
    public Map<String, Object> getPageListBykeyword(Page<Question> pageParam, String keyword) {
        // 获取关键词
        QueryWrapper<Subject> subjectWrapper = new QueryWrapper<>();
        subjectWrapper.ne("parent_id", 0);
        subjectWrapper.select("title", "id");
        List<Subject> list = subjectService.list(subjectWrapper);
        ArrayList<String> resultKeyword = new ArrayList<>();
        for (Subject subject : list) {
            if (keyword.contains(subject.getTitle())) resultKeyword.add(subject.getId());
        }
        QueryWrapper<Question> wrapper = new QueryWrapper<>();
        if (resultKeyword.size() >= 1) {
            wrapper.eq("subject_id", resultKeyword.get(0));
        } else {
            wrapper.eq("subject_id", 99);
        }

        wrapper.orderByDesc("view_count");
        baseMapper.selectPage(pageParam, wrapper);
        List<Question> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();//下一页
        boolean hasPrevious = pageParam.hasPrevious();//上一页

        //把分页数据获取出来，放到map集合
        Map<String, Object> map = new HashMap<>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);
        //map返回
        return map;

    }
}
